﻿<%@ WebHandler Language="C#" Class="UploadHandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using KPIReport.Library.DomainObject.Administration;
using KPIReport.Library.DataAccess.Administration;
using KPIReport.Library.DomainObject.Administration.Catalog;
using KPIReport.Library.DataAccess.Administration.Catalog;

using KPIReport.Web.Support;
using Newtonsoft.Json.Linq;
using Excel;
using System.IO;
using System.Data;

public class UploadHandler : KPIReport.Web.BaseHandler
{

    private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["KpiReportConn"].ConnectionString);
    private MustSellListItemSSRepo MustSellListItemSSDal = new MustSellListItemSSRepo(ConfigurationManager.ConnectionStrings["KpiReportConn"].ConnectionString);
    private customerRepo customerDal = new customerRepo(ConfigurationManager.ConnectionStrings["KpiReportConn"].ConnectionString);
    private ProdukKonversiSatuanRepo ProdukKonversiSatuanDal = new ProdukKonversiSatuanRepo(ConfigurationManager.ConnectionStrings["KpiReportConn"].ConnectionString);
   

    public override void ProcessRequest(HttpContext context)
    {
        string MethodName = string.Empty;
        base.ProcessRequest(context);

        MethodName = context.Request.Params["method"];


        switch (MethodName.Trim())
        {
            case ("uploadMslItem"):
                context.Response.Write(UploadMslItem(context));
                break;
            case ("uploadCustomer"):
                context.Response.Write(UploadCustomer(context));
                break;
            case ("uploadProduct"):
                context.Response.Write(UploadProduct(context));
                break;
            default:
                // do nothing
                break;
        }



    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private string UploadMslItem(HttpContext context)
    {
        JSONHelper helper = new JSONHelper();
         string FileName = string.Empty;
        try
        {

            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;

                var file = context.Request.Files[0];
               
                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = hpf.FileName.Split(new char[] { '\\' });
                    FileName = files[files.Length - 1];
                }
                else
                {
                    FileName = hpf.FileName;
                }

                byte[] datas = new byte[hpf.ContentLength];
                hpf.InputStream.Position = 0;
                hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                string path = context.Server.MapPath("~/Upload/Master/MSLItem/");
                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);

                //FileName = System.IO.Path.Combine(path, FileName);// "DataCabang" + ".xlsx");
                if (System.IO.File.Exists(path+FileName))
                    System.IO.File.Delete(path + FileName);

                hpf.SaveAs(path + FileName);

                hpf.InputStream.Close();
                hpf.InputStream.Dispose();

            }


            //FileStream stream = File.Open(context.Server.MapPath(@"~/Upload/Master/MSLItem/") +FileName, FileMode.Open, FileAccess.Read, FileShare.None);

            ////1. Reading from a binary Excel file ('97-2003 format; *.xls)
            //IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
            ////...
            ////2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
            ////IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
            ////...
            ////3. DataSet - The result of each spreadsheet will be created in the result.Tables
            ////DataSet result = excelReader.AsDataSet();
            ////...
            ////4. DataSet - Create column names from first row
            //excelReader.IsFirstRowAsColumnNames = false;
            //DataSet ds = excelReader.AsDataSet();

            //ExcelReader excelReader = new ExcelReader();
            DataSet ds = ExcelReader.ReadExcel(context.Server.MapPath(@"~/Upload/Master/MSLItem/") + FileName);

            //5. Data Reader methods
            List<MustSellListItemSS> listItemSS = new List<MustSellListItemSS>();
            MustSellListItemSS objItemSS = new MustSellListItemSS();

            List<MustSellListItemSSC> listItemSSC = new List<MustSellListItemSSC>();
            MustSellListItemSSC objItemSSC = new MustSellListItemSSC();

            List<MustSellListItemSupermarketSmallNew> listItemSmall = new List<MustSellListItemSupermarketSmallNew>();
            MustSellListItemSupermarketSmallNew objItemSmall = new MustSellListItemSupermarketSmallNew();

            //foreach (DataRow dr in ds.Tables[0].Rows)
            for(int i=0;i<ds.Tables[0].Rows.Count;i++)
            {
                DataRow dr = ds.Tables[0].Rows[i];
                objItemSS = new MustSellListItemSS();
                objItemSS.KodeProduk = dr[0].ToString().Trim();
                objItemSS.ProductDescription = dr[1].ToString().Trim();
                objItemSS.MSL = dr[2].ToString().Trim();

                listItemSS.Add(objItemSS);

                objItemSSC = new MustSellListItemSSC();
                objItemSSC.KodeProduk = dr[0].ToString().Trim();
                objItemSSC.ProductDescription = dr[1].ToString().Trim();
                objItemSSC.MSL = dr[2].ToString().Trim();

                listItemSSC.Add(objItemSSC);

                objItemSmall = new MustSellListItemSupermarketSmallNew();
                objItemSmall.KodeProduk = dr[0].ToString().Trim();
                objItemSmall.productdescription = dr[1].ToString().Trim();
                objItemSmall.MSL = dr[2].ToString().Trim();

                listItemSmall.Add(objItemSmall);

            }


            ////6. Free resources (IExcelDataReader is IDisposable)
            //excelReader.Close();
            MustSellListItemSSDal.Save(listItemSS,listItemSSC,listItemSmall);

            helper.Message = "Data berhasil di Upload !";
            helper.IsSuccess = true;

        }
        catch (Exception ex)
        {

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }
        finally
        {
            recLog log = new recLog();
            log.LogEvent = "Upload Data Cabang";
            log.LogMessage = helper.Message;
            log.LogSource = "UploadDataHandler.ashx";
            log.CreatedBy = base.UserLoggedIn;
            log.CreatedDate = DateTime.Now;
            logDal.Save(log);

        }

        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

    }

    private string UploadCustomer(HttpContext context)
    {
        JSONHelper helper = new JSONHelper();
        string FileName = string.Empty;
        try
        {

            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;

                var file = context.Request.Files[0];

                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = hpf.FileName.Split(new char[] { '\\' });
                    FileName = files[files.Length - 1];
                }
                else
                {
                    FileName = hpf.FileName;
                }

                byte[] datas = new byte[hpf.ContentLength];
                hpf.InputStream.Position = 0;
                hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                string path = context.Server.MapPath("~/Upload/Master/Customer/");
                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);

                //FileName = System.IO.Path.Combine(path, FileName);// "DataCabang" + ".xlsx");
                if (System.IO.File.Exists(path + FileName))
                    System.IO.File.Delete(path + FileName);

                hpf.SaveAs(path + FileName);

                hpf.InputStream.Close();
                hpf.InputStream.Dispose();

            }


            //FileStream stream = File.Open(context.Server.MapPath(@"~/Upload/Master/MSLItem/") + FileName, FileMode.Open, FileAccess.Read, FileShare.None);

            ////1. Reading from a binary Excel file ('97-2003 format; *.xls)
            //IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
            ////...
            ////2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
            ////IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
            ////...
            ////3. DataSet - The result of each spreadsheet will be created in the result.Tables
            ////DataSet result = excelReader.AsDataSet();
            ////...
            ////4. DataSet - Create column names from first row
            //excelReader.IsFirstRowAsColumnNames = false;
            //DataSet ds = excelReader.AsDataSet();

            //5. Data Reader methods
            List<customer> listCustomer = new List<customer>();
            customer objCustomer = new customer();

            //ExcelReader excelReader = new ExcelReader();
            DataSet ds = ExcelReader.ReadExcel(context.Server.MapPath(@"~/Upload/Master/Customer/") + FileName);
            
            //foreach (DataRow dr in ds.Tables[0].Rows)
            for (int i = 4; i < ds.Tables[0].Rows.Count; i++)
            {
                DataRow dr = ds.Tables[0].Rows[i];
                objCustomer = new customer();
                objCustomer.Customer_Code = dr[0].ToString().Trim();
                objCustomer.Customer_Name = dr[1].ToString().Trim();
                objCustomer.Kode_Outlet_Classification = dr[2].ToString().Trim();
                objCustomer.Outlet_Classification = dr[3].ToString().Trim();
                objCustomer.Customer_Open_Date = dr[4].ToString().Trim();
                objCustomer.Customer_Status = dr[5].ToString().Trim();
                objCustomer.Postal_Code = dr[6].ToString().Trim();
                objCustomer.Kode_Customer_Area = dr[7].ToString().Trim();
                objCustomer.Customer_Area = dr[8].ToString().Trim();
                objCustomer.Address = dr[12].ToString().Trim();
                
                listCustomer.Add(objCustomer);
            }


            
            customerDal.SaveUpload(listCustomer);

            helper.Message = "Data berhasil di Upload !";
            helper.IsSuccess = true;

        }
        catch (Exception ex)
        {

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }
        finally
        {
            recLog log = new recLog();
            log.LogEvent = "Upload Data Cabang";
            log.LogMessage = helper.Message;
            log.LogSource = "UploadDataHandler.ashx";
            log.CreatedBy = base.UserLoggedIn;
            log.CreatedDate = DateTime.Now;
            logDal.Save(log);

        }

        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

    }

    private string UploadProduct(HttpContext context)
    {
        JSONHelper helper = new JSONHelper();
        string FileName = string.Empty;
        try
        {

            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;

                var file = context.Request.Files[0];

                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = hpf.FileName.Split(new char[] { '\\' });
                    FileName = files[files.Length - 1];
                }
                else
                {
                    FileName = hpf.FileName;
                }

                byte[] datas = new byte[hpf.ContentLength];
                hpf.InputStream.Position = 0;
                hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                string path = context.Server.MapPath("~/Upload/Master/Product/");
                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);

               
                if (System.IO.File.Exists(path + FileName))
                    System.IO.File.Delete(path + FileName);

                hpf.SaveAs(path + FileName);

                hpf.InputStream.Close();
                hpf.InputStream.Dispose();

            }



            //5. Data Reader methods
            List<ProdukKonversiSatuan> listProduk = new List<ProdukKonversiSatuan>();
            ProdukKonversiSatuan objProduk = new ProdukKonversiSatuan();

            //ExcelReader excelReader = new ExcelReader();
            DataSet ds = ExcelReader.ReadExcel(context.Server.MapPath(@"~/Upload/Master/Product/") + FileName);

            //foreach (DataRow dr in ds.Tables[0].Rows)
            for (int i = 2; i < ds.Tables[0].Rows.Count; i++)
            {
                DataRow dr = ds.Tables[0].Rows[i];
                objProduk = new ProdukKonversiSatuan();
                objProduk.KodeProduk = dr[0].ToString().Trim().Replace("#","").Replace("*","");
                objProduk.NamaProduk = dr[1].ToString().Trim();
                objProduk.Status = dr[2].ToString().Trim();
                objProduk.BaseProduk = dr[6].ToString().Trim();
                objProduk.CasePallet = dr[11].ToString().Trim()==""?0:Convert.ToInt32(dr[11].ToString().Trim().Replace(".00",""));
                objProduk.DSPCase = dr[13].ToString().Trim() == "" ? 0 : Convert.ToInt32(dr[13].ToString().Trim().Replace(".00", ""));
                objProduk.EACase = dr[14].ToString().Trim() == "" ? 0 : Convert.ToInt32(dr[14].ToString().Trim().Replace(".00", ""));
                

                listProduk.Add(objProduk);
            }



            ProdukKonversiSatuanDal.SaveUpload(listProduk);

            helper.Message = "Data berhasil di Upload !";
            helper.IsSuccess = true;

        }
        catch (Exception ex)
        {

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }
        finally
        {
            recLog log = new recLog();
            log.LogEvent = "Upload Data Product";
            log.LogMessage = helper.Message;
            log.LogSource = "UploadHandler.ashx";
            log.CreatedBy = base.UserLoggedIn;
            log.CreatedDate = DateTime.Now;
            logDal.Save(log);

        }

        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

    }
}